package com.tang.imgupload.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class RabbitMQUtil {

	@Autowired
	RabbitTemplate rabbitTemplate;

	public void send(Object data, String exchange, String routingKey) throws JsonProcessingException{
		String messageId = String.valueOf(UUID.randomUUID());
		String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		Map<String, Object> map = new HashMap<>();
		map.put("messageId", messageId);
		String datajson = new ObjectMapper().writeValueAsString(data);
		map.put("messageData", datajson);
		map.put("createTime", createTime);
		//将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
		rabbitTemplate.convertAndSend(exchange, routingKey, map);
	}
}
